﻿using System;
using System.Configuration;
using System.Security.Cryptography;
using System.Text;

namespace S3Upload.Models
{
    public class UploadModel
    {
        #region Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="UploadModel" /> class.
        /// </summary>
        public UploadModel()
        {
            string policyString = string.Format(
                "{{"+ 
                "\"expiration\": \"{0}.000Z\","+
                "\"conditions\": [" +
                    "{{\"bucket\": \"{1}\" }},"+
                    "{{\"acl\": \"public-read\" }},"+
                    "{{\"success_action_status\": \"201\" }},"+
                    "[\"starts-with\", \"$key\", \"upload\"]," + // Upload to folder "upload"
                    "[\"starts-with\", \"$Filename\", \"\"]," +
                    "[\"content-length-range\", 0, 524288000]" +
                "]"+
            "}}", DateTime.UtcNow.AddDays(1).ToString("s"), Bucket);
            

            // Create Policy
            ASCIIEncoding encoding = new ASCIIEncoding();
            byte[] policyBytes = encoding.GetBytes(policyString);
            Policy = Convert.ToBase64String(policyBytes);


            // Create Signature via Secret Key & Policy
            byte[] base64PolicyBytes = encoding.GetBytes(Policy);
            byte[] secretKeyBytes = encoding.GetBytes(SecretKey);
            HMACSHA1 hmacsha1 = new HMACSHA1(secretKeyBytes);
            byte[] signatureBytes = hmacsha1.ComputeHash(base64PolicyBytes);
            Signature = Convert.ToBase64String(signatureBytes);
        }

        #endregion



        #region Public Properties

        public string Policy { get; set; }
        public string Signature { get; set; }

        public string AccessKey
        {
            get { return ConfigurationManager.AppSettings["AmazonAccessKey"]; }
        }

        public string SecretKey
        {
            get { return ConfigurationManager.AppSettings["AmazonSecretKey"]; }
        }

        public string Bucket
        {
            get { return ConfigurationManager.AppSettings["AmazonS3Bucket"]; }
        }

        #endregion
    }

}